package com.mapreduce.mapjoin;

import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class DistributedMapper extends Mapper<LongWritable, Text,Text, NullWritable>{//
    //存放产品的Map集合
   private Map<String,String> pMap = new HashMap();
   //map输出的key
   private Text keyOut = new Text();
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        // 获取缓存文件，并把文件pd.txt内容封装到集合
        URI[] cacheFiles = context.getCacheFiles();
        FileSystem fs = FileSystem.get(context.getConfiguration());
        FSDataInputStream fsd = fs.open(new Path(cacheFiles[0]));
        //从流中读取数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(fsd, "UTF-8"));
        String line ;
        while ((line=reader.readLine())!=null){
            //01	小米
            String[] data = line.split("\t");
            // 01:小米
            pMap.put(data[0],data[1]);

        }
        //关流
        reader.close();

    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //1001	01	1
        String line = value.toString();
        String[] data1 = line.split("\t");
        // 订单id  产品名称   销量
       String  content = data1[0]+"\t"+pMap.get(data1[1])+"\t"+data1[2];
        keyOut.set(content);
        context.write(keyOut,NullWritable.get());
    }
}
